<?php
class Enrollment Extends MY_Controller
{
	var $test_repo;
	var $profile_data;
	var $user_data;
	public function __construct()
	{
		parent::__construct();
		$this->load->model(array('M_levels','M_users','M_new_enrollee','M_for_enrollment_id'));
		$this->load->library(array('authlink','create_captcha','token'));
		$this->_generate_transaction();
	}
	
	public function index()
	{
		$this->_check_transaction();
		$this->load->helper('file');//load helper file
		delete_files('./captcha');// delete all images in captcha folder
		$captcha = $this->create_captcha->_captcha();
		$this->session->set_flashdata('image_url',$captcha->link);
		$this->session->set_userdata('enrollment_finished',FALSE);
		$this->session->set_userdata('enrollment_type',NULL);
		$this->authlink->clear_authlink();
		$this->session->set_userdata('captchaword',$captcha->word);
		$this->view_data['question'] = $captcha->image;
		$this->view_data['system_message'] = $this->_msg();
		$this->view_data['token'] = $this->token->get_token();
	}
	
	public function enrollment_procedure()
	{	
		$this->_check_transaction();
		$this->disable_browser_cache = TRUE;
		$this->form_validation->set_rules('captcha_answer','','trim|htmlspecialchars');
		//$this->form_validation->set_rules('option','','trim|htmlspecialchars');
		$this->form_validation->set_rules('sdj','','trim|htmlspecialchars');
		//check proper form input
		//if($this->input->post('enrollment_type') !== FALSE)
		//{
			//check post ID
			//if($this->input->post('option') !== FALSE )
			//{
				//check form token
				if($this->token->validate_token($this->input->post('sdj')))
				{
					$captcha_fs = $this->session->userdata('captchaword');
					if(STRTOLOWER($captcha_fs) == STRTOLOWER($this->input->post('captcha_answer')))
					{
						//switch($option = $this->input->post('option'))
						//{
							//case $option == 'new':
								$this->session->set_userdata('enrollment_finished',FALSE);
								$this->session->set_userdata('enrollment_type','NEW');
								redirect('new_student');
							//break;
							//case $option == 'old':
								//$this->session->set_userdata('enrollment_type','OLD');
								//$this->session->set_userdata('enrollment_finished',FALSE);
								//redirect('old');
							//break;
						//}
					}else{
						$captcha = $this->create_captcha->_captcha();
						$this->token->reset();
						$this->session->set_userdata('captchaword',$captcha->word);
						$this->_msg('e','Invalid Captcha Answer','new_student');
					}
				}else{
					$this->_msg('e','Invalid Token','new_student');
				}
			//}else{
				//$captcha = $this->create_captcha->_captcha();
				//$this->token->reset();
				//$this->session->set_userdata('captchaword',$captcha->word);
				//redirect('enrollment');
			//}
		//}else{
			//$captcha = $this->create_captcha->_captcha();
			//$this->token->reset();
			//$this->session->set_userdata('captchaword',$captcha->word);
			//redirect('enrollment');
		//}
	}
	
	public function registration_form($e_id)
	{
		//$this->_check_transaction();
		$this->disable_browser_cache = TRUE;
		$this->view_data['system_message'] = $this->_msg();
		$this->view_data['class_error'] = NULL;
		$this->view_data['token'] = $this->token->get_token();
		$this->view_data['cannot_be_with'] = '';
		$this->view_data['error_number_1'] = '';
		$this->view_data['error_number_2'] = '';
		$this->view_data['error_number_3'] = '';
		$this->view_data['error_number_4'] = '';
		$this->view_data['to_be_display_father'] = NUll;
		$this->view_data['to_be_display_mother'] = NUll;
		
		//if($this->session->userdata('enrollment_type') == 'NEW'):
			//if($this->session->userdata('enrollment_finished') == FALSE):
				$this->load->helper('misc');
				$this->view_data['levels'] = $this->M_levels->get_all_levels_array();
				$this->form_validation->set_error_delimiters('<span class="error_simple">', '</span>');
			
				if($this->input->post('fillup_let_be') !== FALSE):
					if($this->token->validate_token($this->input->post('let_be_lefg'))):
						//$this->form_validation->set_error_delimiters('<span class="error_simple">', '</span>');
						//$this->form_validation->set_message('required', 'This field is required.');
						$with_guardian = $this->input->post('living_in_ph_with_guardian');
						$fatherchecked = $this->input->post('living_in_ph_with_father');
						$motherchecked = $this->input->post('living_in_ph_with_mother');
						$nationality = $this->input->post('child_nationality');
						$father = $this->input->post('to_be_display_father');
						$mother = $this->input->post('to_be_display_mother');
						$fathermother = $father.'_'.$mother;
						$this->view_data['to_be_display_father'] = $father;
						$this->view_data['to_be_display_mother'] = $mother;
						
						if($fatherchecked=='yes' || $motherchecked=='yes' || $with_guardian=='yes'):
							$cannot_be_with = 'yes';
						else:
							$cannot_be_with = 'no';
						endif;
						
						if($with_guardian == 'yes'):
							$with_guardian_validation = 'enrollment_profile_2';
						else:
							$with_guardian_validation = 'enrollment_profile';
						endif;
						if($nationality == 'other'):
							$nationality_validation = 'nationality2';
						else:
							$nationality_validation = 'nationality1';
						endif;
						$all = 'new_'.$nationality_validation.'_'.$with_guardian_validation.'_'.$fathermother;
						
						if($this->form_validation->run($all) !== FALSE && $cannot_be_with=='yes'):
							
							$e_profile_id = $this->input->post('e_profile_id');
							$profile = $this->input->post();
							unset($profile['fillup_let_be']);
							
							if($this->M_users->update_complete_info($profile,$e_profile_id) == TRUE)
							{
								
								$level_id = $profile['level_id'];
								$this->load->library('idno_creator');
								$generated_studentid = $this->idno_creator->generate_new_id_compressed($level_id);
								//$for_enrollment_table['e_profile_id']  = $profile_id= $this->M_users->get_last_insert_id();
								$for_enrollment_table['e_grade_level'] 	 = $level_id;
								$for_enrollment_table['e_student_id'] = $generated_studentid;
								//$for_enrollment_table['e_enrollee_type'] = 'new';
								$for_enrollment_table['enrollment_transaction_code'] = NULL;
								$for_enrollment_table['mustverify'] = NULL;
								
								//insert Enrollee
								if($this->M_new_enrollee->update_enrolle($for_enrollment_table,$e_id) == TRUE)
								{
								
									//$current_id = $this->M_for_enrollment_id->get_enrollment_id();
									//if(intval($profile['student_number']) == intval($current_id->for_e_id)){
										//$data['for_e_id'] = intval($generated_studentid->for_e_id) + 1;
										//$this->M_for_enrollment_id->update_enrollment_id($data);
									//}
									$enroll_id = $e_id;

									//generate fees
									//$this->M_new_enrollee->get_fees_set_for_current_level($level_id,$enroll_id,$this->current_grading_period,$profile['e_ay_id'],'new');
									//if($profile['child_nationality'] == 'other'){
										//$child_nationality = strtolower($profile['child_nationality2']);
									//}else{
										//$child_nationality = strtolower($profile['child_nationality']);
									//}
									//if($child_nationality!='filipino' && $child_nationality!='pinoy' && $child_nationality!='pinay' && $child_nationality!='pilipino' && $child_nationality!='phil-am' && $child_nationality!='fil-am'):
										//$this->M_new_enrollee->get_set_foreign_fee($enroll_id,$this->current_grading_period,$this->current_school_year);
									//endif;
									$auth = $this->authlink->generate_authlink();
									$message ='Your data was successfully saved. Please visit the school for payments and further instructions.';
									$this->_msg('s',$message,'status/success/'.$auth);
									
								}else{
									$auth = $this->authlink->generate_authlink();
									$error_number = time().'-'.uniqid(rand(1000,9999));
									$message ='An Error has occured. System failed to insert student: '.$profile['child_fname'].'. Error Number: ('.$error_number.')';
									$message2 ='An Error has occured. System failed to insert student: '.$profile['child_fname'].' in the enrollment table. Error Number: ('.$error_number.')';
									log_message('error',$message2);
									$this->_msg('e',$message,'enrollment/registration_form/'.$e_id);
								}
							}else{
								$auth = $this->authlink->generate_authlink();
								$error_number = time().'-'.uniqid(rand(1000,9999));
								$message ='An Error has occured. System failed to insert student: '.$profile['child_fname'].'. Error Number: ('.$error_number.')';
								$message2 ='An Error has occured. System failed to insert student: '.$profile['child_fname'].' in the profile table. Error Number: ('.$error_number.')';
								log_message('error',$message2);
								$this->_msg('e',$message,'enrollment/registration_form/'.$e_id);
							}
							
						else:
							$form_1 = array('email','level_id','child_fname','child_mname','child_lname','child_nickname','child_name_ext','gender','child_bdate','child_nationality','child_placeofbirth','child_city_address','child_telno','mobile_phone','child_religous','living_in_ph_with_father','living_in_ph_with_mother','living_in_ph_with_guardian','childs_english_reading_writing_level','childs_english_verbal_proficiency','language_at_home','participation_in_advanced_level_classes','remedial_help_in_previous_schools','special_talent_interest_dance','special_talent_interest_drama','special_talent_interest_art','special_talent_interest_acomputer','special_talent_interest_vocal_chorus','special_talent_interest_athletics','special_talent_interest_athletics_spec','special_talent_interest_band','special_talent_interest_band_spec','special_talent_interest_string','special_talent_interest_string_spec','hinder_childs_learning','leave_school','previous_school','previous_school_address','previous_grade_level','guardian_name','guardian_mname','guardian_lname','guardian_citizenship','guardian_visa','guardian_occup','guardian_office_tel','guardian_contact_no','guardian_contact_no_text','student_number','child_nationality2');
							$form_2 = array('father_name','father_mname','father_lname','father_citizenship','father_visa','father_occup','father_office_tel','father_contact_no','father_contact_no_text','step_father_name','step_father_mname','step_father_lname','step_father_citizenship','step_father_visa','step_father_occup','step_father_office_tel','step_father_contact_no','step_father_contact_no_text','mother_name','mother_mname','mother_lname','mother_citizenship','mother_visa','mother_occup','mother_office_tel','mother_contact_no','mother_contact_no_text','step_mother_name','step_mother_mname','step_mother_lname','step_mother_citizenship','step_mother_visa','step_mother_occup','step_mother_office_tel','step_mother_contact_no','step_mother_contact_no_text');
							$form_3 = array('allergies_reaction','drug_allergies_reaction','asthma','asthma_inhaler','eye_problem_spec','ear_problem_spec','major_ailment','recently_hospitalized','major_injury','medication_child_taking_spec','medication_child_taking_school_hours');
							$form_4 = array('authfirst_aid','auth_emergency','auth_emergency_nearest_hosp','auth_oral_non_presc','first_permission','second_permission','third_permission');
							$error_number_1 = $this->form_validation->error_exists($form_1);
							$error_number_2 = $this->form_validation->error_exists($form_2);
							$error_number_3 = $this->form_validation->error_exists($form_3);
							$error_number_4 = $this->form_validation->error_exists($form_4);
							
							if($cannot_be_with == 'no'):
								$this->view_data['error_number_1'] = $error_number_1+1;
							else:
								$this->view_data['error_number_1'] = $error_number_1;
							endif;
							$this->view_data['error_number_2'] = $error_number_2;
							$this->view_data['error_number_3'] = $error_number_3;
							$this->view_data['error_number_4'] = $error_number_4;
							$this->view_data['system_message'] = $this->_msg('e','Please fix the errors below.');
							$this->view_data['cannot_be_with'] = $cannot_be_with;
						endif;
					else:
						$this->token->restart();
						$this->_msg('e','Token expired or compromised.','new_register/'.$e_id);
					endif;
					
				endif;
			
			//else:
			//	redirect('new_register');
			//endif;
		//else:
		//	redirect('new_register');
		//endif;
	
		/*
		$this->_check_transaction();
		$this->disable_browser_cache = TRUE;
		$this->view_data['system_message'] = $this->_msg();
		$this->view_data['class_error'] = NULL;
		$this->view_data['token'] = $this->token->get_token();
		$this->view_data['cannot_be_with'] = '';
		
		if($this->session->userdata('enrollment_type') == 'NEW')
		{
			if($this->session->userdata('enrollment_finished') == FALSE)
			{
				$this->load->helper('misc');
				$this->view_data['levels'] = $this->M_levels->get_all_levels_array();
				$this->form_validation->set_error_delimiters('<span class="error_simple">', '</span>');
				
				if($this->input->post('fillup_profile') !== FALSE)
				{
					if($this->token->validate_token($this->input->post('sdf_loc')))
					{
						$this->form_validation->set_message('required', 'This field is required.');
						$with_guardian = $this->input->post('living_in_ph_with_guardian');
						$fatherchecked = $this->input->post('living_in_ph_with_father');
						$motherchecked = $this->input->post('living_in_ph_with_mother');
						$nationality = $this->input->post('child_nationality');
						if($fatherchecked=='yes' || $motherchecked=='yes' || $with_guardian=='yes')
						{
							$cannot_be_with = 'yes';
						}else{
							$cannot_be_with = 'no';
						}
						if($with_guardian == 'yes')
						{
							if($nationality == 'other'):
								$with_guardian_validation = 'nationality2_enrollment_profile_2';
							else:
								$with_guardian_validation = 'enrollment_profile_2';
							endif;
						}else{
							if($nationality == 'other'):
								$with_guardian_validation = 'nationality2_enrollment_profile';
							else:
								$with_guardian_validation = 'enrollment_profile';
							endif;
						}
						if($this->form_validation->run($with_guardian_validation) !== FALSE && $cannot_be_with=='yes')
						{
							$profile = $this->input->post();
							unset($profile['fillup_profile']);

							if($this->M_users->register_user($profile) == TRUE)
							{
								$level_id = $profile['level_id'];
								$this->load->library('idno_creator');
								$generated_studentid = $this->idno_creator->generate_new_id_compressed($level_id);
								$for_enrollment_table['e_profile_id']  = $profile_id= $this->M_users->get_last_insert_id();
								$for_enrollment_table['e_grade_level'] 	 = $level_id;
								$for_enrollment_table['e_student_id'] = $generated_studentid;
								$for_enrollment_table['e_enrollee_type'] = 'new';
								$for_enrollment_table['enrollment_transaction_code'] = NULL;
								$for_enrollment_table['mustverify'] = NULL;
								$emailer= $profile['email'];
								
								if($this->M_school_settings->check_email_verification() == TRUE)
								{
								
									if($this->M_users->check_my_mail($emailer,$profile_id) == TRUE)
									{
										$for_enrollment_table['verified'] = 1;
									}
								
								}else{
								
									$for_enrollment_table['verified'] = 1;
								
								}
								
								//insert Enrollee
									if($this->M_new_enrollee->enroll_new_student($for_enrollment_table) == TRUE)
									{
										
										//insert student id to database for record keeping on used student id's
										// $this->M_new_enrollee->count_id($generated_studentid,$prof['level_id']);
										//$data['for_e_id'] = intval($generated_studentid->for_e_id) + 1;
										//$this->M_for_enrollment_id->update_enrollment_id($data);
										$enroll_id = $this->M_new_enrollee->get_last_input_id();
										$for_enrollment_table['profile_id']  = $profile_id;
										$for_enrollment_table['enrollment_id'] = $enroll_id;
										$for_enrollment_table['child_lname'] = $profile['child_lname'];
										$for_enrollment_table['child_fname'] =$profile['child_fname'];
										$for_enrollment_table['child_mname'] =$profile['child_mname'];
										$for_enrollment_table['emailaddress'] =$profile['email'];
										//generate fees
										if($this->M_new_enrollee->get_fees_set_for_current_level($level_id,$enroll_id,$this->current_grading_period,$this->current_school_year,'new') !== FALSE)
										{
											$this->M_new_enrollee->get_fees_set_for_foreign($level_id,$enroll_id,$this->current_grading_period,$this->current_school_year,'new');
											$this->session->set_userdata('profilesettings',$for_enrollment_table);
											$this->session->set_userdata('enrollmentstep',5);
											$this->_msg('s','Part 1 completed','pli');
										}
									}
							}else{
								$auth = $this->authlink->generate_authlink();
								$error_number = time().'-'.uniqid(rand(1000,9999));
								$message ='An Error has occured, System failed to insert student: '.$profile['child_fname'].' Error Number: ('.$error_number.')';
								log_message('error',$message);
								$this->_msg('e',$message,'status/error/'.$auth);
							}
						}else{
								$this->view_data['system_message'] = $this->_msg('e','Please fix the errors below.');
								$this->view_data['cannot_be_with'] = $cannot_be_with;
						}
					}else{
						$this->token->restart();
						$this->_msg('e','Token expired or compromised.','register');
					}
				}
			}else{
				redirect('enrollment');
			}
		}else{
			redirect('enrollment');
		}
		*/

		$this->view_data['applicant'] = $this->M_new_enrollee->get_applicant($e_id);
		$this->view_data['e_id'] = $e_id;
	}
	
	public function developmental_history()
	{
		$this->_check_transaction();
		$this->disable_browser_cache = TRUE;
		$this->view_data['system_message'] = $this->_msg();
		$this->view_data['class_error'] = NULL;
		$this->view_data['token'] = $this->token->get_token();
		
		if($this->session->userdata('enrollmentstep') == 2)
		{
			$this->form_validation->set_error_delimiters('<span class="error_simple">', '</span>');
			if($this->form_validation->run('developmental_history') !== FALSE)
			{
				$this->load->helper('misc');
				$this->form_validation->set_error_delimiters('<span class="error_simple">', '</span>');
				
				if($this->input->post('fillup_developmental') !== FALSE)
				{
					if($this->token->validate_token($this->input->post('spm_sdf')))
					{
						$prof = $this->session->userdata('profilesettings');				
						$developmental = $this->input->post();
						unset($developmental['fillup_developmental']);
						$this->session->set_userdata('enrollmentstep',3);
						$this->M_new_enrollee->add_further_profile_value($developmental,$prof['profile_id'],'dev');
						$this->_msg('s','Part 2 completed','health');
					}else{
						$this->token->reset();
						$this->_msg('e','Token expired or been compromised. Please restart again.','developmental');
					}
				}
			}else{
				if(validation_errors() !== '')
				{
					$this->view_data['system_message'] = $this->_msg('e','Please fix the errors below.');
				}
			}
		}else{
			redirect('register');
		}
	}
	
	public function health_history()
	{
		$this->_check_transaction();
		$this->disable_browser_cache = TRUE;
		$this->view_data['system_message'] = $this->_msg();
		$this->view_data['class_error'] = NULL;
		$this->view_data['token'] = $this->token->get_token();
		$this->form_validation->set_error_delimiters('<span class="error_simple">', '</span>');
		if($this->session->userdata('enrollment_type') == 'NEW')
		{
			$this->form_validation->set_error_delimiters('<span class="error_simple">', '</span>');
			if($this->session->userdata('enrollmentstep') == 3)
			{
				if($this->form_validation->run('healthhistory') !== FALSE)
				{
					$this->load->helper('misc');
					$this->form_validation->set_error_delimiters('<span class="alert-box">', '</span>');
					
					if($this->input->post('fillup_health') !== FALSE)
					{
						if($this->token->validate_token($this->input->post('sdj_lefg')))
						{
							$health = $this->input->post();
							$prof = $this->session->userdata('profilesettings');
							$this->session->set_userdata('enrollmentstep',6);
							$this->M_new_enrollee->add_further_profile_value($health,$prof['profile_id'],'hlth');
							$this->_msg('s','Part 3 completed','let_be');
						}else{
							$this->token->restart();
							$this->_msg('e','Token expired or been compromised. Please restart again','health');
						}
					}
				}else{
					if(validation_errors() !== '')
					{
						$this->view_data['system_message'] = $this->_msg('e','Please Fix the errors Below.');
					}
				}
			}else{
				redirect('enrollment');
			}
		}else{
			redirect('enrollment');
		}
	}
	
	public function enrollment_finished()
	{
		$this->_check_transaction();
		if($this->session->userdata('enrollmentstep') == 4)
		{
			$prof = $this->session->userdata('profilesettings');
			$developmental = $this->session->userdata('enrolldevelopmental');
			$health = $this->session->userdata('enrollhealth');
			$this->load->library('idno_creator');
			
			//$generated_studentid = $this->idno_creator->generate_new_id_compressed($prof['level_id']);
			
			//$input['password'] = substr(sha1(rand(10000,99999)),4,9);
			//$input['e_profile_id']= $prof['profile_id'];
			//$input['e_enrollee_type'] = 'new' ;
			//$input['e_grade_level'] =  $prof['level_id'];
			//$input['e_student_id'] = $generated_studentid;
			$input['enrollment_transaction_code'] =  substr(base64_encode(sha1(time().rand(10,99).md5(time().rand(100,200)))),0,15);
			$input['mustverify'] = time() + 24*60*60;
			$auth = $this->authlink->generate_authlink();
			
			$enroll_id = $prof['enrollment_id'];
			//$verified = $prof['verified'];
			
			//check if validate by email
			if($this->M_school_settings->check_email_verification() == TRUE)
			{
				//insert Enrollee
				//if($this->M_new_enrollee->enroll_new_student($input) == TRUE)
				//{
					//insert student id to database for record keeping on used student id's
					// $this->M_new_enrollee->count_id($generated_studentid,$prof['level_id']);
					
					//$enroll_id = $this->M_new_enrollee->get_last_input_id();
					//$level_id = $prof['level_id'];
					
					//generate fees
					//if($this->M_new_enrollee->get_fees_set_for_current_level($level_id,$enroll_id,$this->current_grading_period,$this->current_school_year) !== FALSE)
					//{
					
					//if($verified == 1){
					
						$auth = $this->authlink->generate_authlink();
						$message ='Your data was successfully saved. Please visit the school for payments and further instructions.';
						$this->_msg('s',$message,'status/success/'.$auth);
					
					//}
					//else
					//{
					
						//$id = $enroll_id.'_'.rand(1000,9999);
						////$c_auth = $this->authlink->hash_make($enroll_id.$id.$input['enrollment_transaction_code']);
						//$link = site_url('confirm/validate/'.$id.'/'.$input['enrollment_transaction_code'].'/'.$c_auth);

						/*$this->_email_student_confirmation_link(
							$prof['child_lname'],
							$prof['child_fname'],
							$prof['child_mname'],
							$link,
							$prof['emailaddress']
						);*/

						//$auth = $this->authlink->generate_authlink();
						//$message ='<h2 class="label success">Application Form Complete.</h2><br /> Please check your email address, '.$prof['emailaddress'].', for further instructions. If you do not receive a message in your Inbox, kindly check your SPAM folder and change email permissions to allow your email to accept emails from the Westfields International School System. Thank you.';
						//$this->token->destroy_token();
						//$this->session->set_userdata('enrollmenttransaction',FALSE);
						//$this->_msg('s',$message,'status/success/'.$auth);
						
					//}
						
					//}
				//}
				
			}else{
				//$input['verified'] = 1;
				//if($this->M_new_enrollee->enroll_new_student($input) == TRUE)
				//{
					//$enroll_id = $this->M_new_enrollee->get_last_input_id();
					//$level_id = $prof['level_id'];
					
					//generate fees
					//if($this->M_new_enrollee->get_fees_set_for_current_level($level_id,$enroll_id,$this->current_grading_period,$this->current_school_year) !== FALSE)
					//{
						$auth = $this->authlink->generate_authlink();
						$message ='Your data was successfully saved. Please visit the school for payments and further instructions.';
						$this->_msg('s',$message,'status/success/'.$auth);
					//}
				//}
			}
		}else{
			redirect('let_be');
		}
	}
	
	public function parent_legal_information()
	{
		$this->_check_transaction();
		$this->disable_browser_cache = TRUE;
		$this->view_data['system_message'] = $this->_msg();
		$this->view_data['class_error'] = NULL;
		$this->view_data['token'] = $this->token->get_token();
		$this->view_data['to_be_display_father'] = NUll;
		$this->view_data['to_be_display_mother'] = NUll;
		
		if($this->session->userdata('enrollmentstep') == 5)
		{
			if($this->input->post('fillup_parent_legal_information') !== FALSE)
			{
			if($this->token->validate_token($this->input->post('tkn_pli')))
			{
			$father = $this->input->post('to_be_display_father');
			$mother = $this->input->post('to_be_display_mother');
			$fathermother = $father.'_'.$mother;
			$this->view_data['to_be_display_father'] = $father;
			$this->view_data['to_be_display_mother'] = $mother;

			$this->form_validation->set_error_delimiters('<span class="error_simple">', '</span>');
			if($this->form_validation->run($fathermother) === TRUE)
			{
				
				$this->load->helper('misc');
				
					
						$prof = $this->session->userdata('profilesettings');			
						$pli = $this->input->post();
						$this->session->set_userdata('enrollmentstep',3);
						$this->M_new_enrollee->add_further_profile_value($pli,$prof['profile_id'],'pli');
						$this->_msg('s','Part 2 completed','health');
			}else{
				if(validation_errors() !== '')
				{
					$this->view_data['system_message'] = $this->_msg('e','Please fix the errors below.');
				}
			}
			}else{
				$this->token->reset();
				$this->_msg('e','Token expired or been compromised. Please restart again','pli');
			}
			}
		}else{
			redirect('register');
		}
	}
	
	public function let_be()
	{
		$this->_check_transaction();
		$this->disable_browser_cache = TRUE;
		$this->view_data['system_message'] = $this->_msg();
		$this->view_data['class_error'] = NULL;
		$this->view_data['token'] = $this->token->get_token();
		
		if($this->session->userdata('enrollmentstep') == 6)
		{
			$this->form_validation->set_error_delimiters('<span class="error_simple">', '</span>');
			if($this->form_validation->run('let_be') !== FALSE)
			{
				$this->load->helper('misc');
				$this->form_validation->set_error_delimiters('<span class="error_simple">', '</span>');
				
				if($this->input->post('fillup_let_be') !== FALSE)
				{
					if($this->token->validate_token($this->input->post('let_be_lefg')))
					{
						$prof = $this->session->userdata('profilesettings');				
						$let_be = $this->input->post();
						$this->session->set_userdata('enrollmentstep',4);
						$this->M_new_enrollee->add_further_profile_value($let_be,$prof['profile_id'],'auth');
						$this->_msg('s','Enrollment Finished','done');
					}else{
						$this->token->reset();
						$this->_msg('e','Token expired or been compromised. Please restart again.','let_be');
					}
				}
			}else{
				if(validation_errors() !== '')
				{
					$this->view_data['system_message'] = $this->_msg('e','Please Fix the errors Below.');
				}
			}
		}else{
			redirect('register');
		}
	}
	
	
/*############################################## OLD STUDENT ENROLLEE ################################################################## */	

	public function old_enrollee()
	{
		$this->_check_transaction();
		$this->disable_browser_cache = TRUE;
		$this->load->library('token');
		$this->token->set_token();
		$this->view_data['form_token'] = $this->token->get_token();
		if($this->input->post('old_enrollee'))
		{
			if($this->token->validate_token($this->input->post('form_token')) == TRUE)
			{
				$this->form_validation->set_rules('idno','ID Number','required|alpha_dash_space');
				
				if($this->form_validation->run() !== FALSE)
				{
					$this->load->model('M_old_enrollee','moe');
					
					$the_id = trim(htmlspecialchars($this->input->post('idno')));
					$result = $this->moe->check_student_id($the_id);
					if($result['status'] == TRUE)
					{
						$this->session->set_userdata(array('e_id'=>$result['enrollment_id'],'p_id'=>$result['profile_id']));
						$hash = $this->authlink->hash_make($the_id);
						$auth = $this->authlink->generate_authlink();
						redirect('enrollment/verify/old/'.$the_id.'/'.$auth.'/'.$hash);
					}else{
						$this->view_data['system_message'] = $this->_msg('n',$result['log']);
					}
				
				}
				if(validation_errors() !== '')
				{
					$this->view_data['system_message'] = $this->_msg('e',validation_errors());
				}
			}else{
				$this->view_data['system_message'] = $this->_msg('e','Invalid token submit!');
			}
		}else{
			$this->view_data['system_message'] = $this->_msg('n','Old students, please enter your ID Number to enroll.');
		}
	}
	
	
	public function verify($type=FALSE,$student_id=FALSE,$auth=FALSE,$hash=FALSE)
	{
		$this->_check_transaction();
		$this->disable_browser_cache = TRUE;
		if($this->authlink->verify_authlink($auth) AND $this->authlink->check_hash_make($student_id,$hash) AND $type AND $student_id)
		{
			$this->view_data['system_message'] = $this->_msg();
			$this->load->library('token');
			$this->view_data['question'] = $this->quest_captcha->get_question();
			$this->view_data['form_token'] = $this->token->get_token();
			$this->view_data['student_id'] = $student_id;
			$this->view_data['auth'] = $auth;
			$this->view_data['hash'] = $hash;
		
			if($this->input->post('verify_old_enrollee'))
			{
				if($this->token->validate_token($this->input->post('form_token')))
				{
					if($this->quest_captcha->check_answer($this->input->post('captcha_answer')))
					{
						$this->form_validation->set_rules('fname','Firstname','required');
						$this->form_validation->set_rules('lname','Lastname','required');
						$this->form_validation->set_rules('password','Password','required');
					
						if($this->form_validation->run() !== FALSE)
						{
							$this->load->model('M_old_enrollee','moe');
							$this->load->model('M_users','mu');
							
							$student_input['fname'] = $this->input->post('fname');
							$student_input['lname'] = $this->input->post('lname');
							$student_input['password'] = $this->input->post('password');

							$search_student = (object)$this->moe->verify_student_credentials($student_input,$student_id);
							
							if($search_student->status == TRUE)
							{
								//insert enrollee to enrollments table and update enrollee archive status
								$result = $this->moe->create_old_enrollee($student_id);
								if($result->status == TRUE)
								{
									$e = $this->moe->return_data();
									if($this->M_new_enrollee->get_fees_set_for_current_level($e->level_id,$e->id,$this->current_grading_period,$this->current_school_year))
									{
										$this->quest_captcha->reset_question();
										$this->_msg('s',$result->log,'enrollment');
									}else{
										$this->authlink->clear_authlink();
										$this->quest_captcha->reset_question();
										$this->_msg('n','You are now registered and an error occured while attempting to calculate your fees.','enrollment');
									}
								}else{
									$this->quest_captcha->reset_question();
									$this->_msg('n',$result->log,'enrollment/verify/'.array_url(array($type,$student_id,$auth,$hash)));
								}
							}
							else{
								$this->quest_captcha->reset_question();
								$this->_msg('e','Credentials entered did not match any from our database.','enrollment/verify/'.array_url(array($type,$student_id,$auth,$hash)));
							}	
						}
					}else{
						$this->quest_captcha->reset_question();
						$this->_msg('e','Wrong captcha answer.','enrollment/verify/'.array_url(array($type,$student_id,$auth,$hash)));
					}
				}
			}
		}else{
			echo 'Not ok';
		}
	}
	
	
	/*############################################## END OLD STUDENT ENROLLEE ################################################################## */	

	
	/* +-----------------------------------------------------
	   | Misc methods used for enrollment
	   +----------------------------------------------------
	*/
	
	private function _email_student_confirmation_link($last_name,$first_name,$middle_name,$link,$email_add)
	{
		$school_name = ucwords($this->school_name);
		$school_name_title = $this->_accronymizer($this->school_name).'@DONOTREPLY.com';
		$fullname = strtoupper($first_name.'-'.$middle_name.'-'.$last_name);
		
			$message = "";
			$message .= "<span style='font-size:10px;'>Note: This message is system-generated, Please do not reply.</span>";
			$message .= "<br /><br />";
			$message .= "Dear {$fullname}, <br /><br />";
			$message .= "Greetings from {$school_name}! <br /><br />";
			//$message .= "Thank you for enrolling at {$school_name}. You just made the right choice!,\n\n";
			$message .= "You have just completed the first step of the enrollment procedure. You would need to verify your enrollment to receive your personal account access.\r\n\r\n";
			$message .= "<br /><br />";
			$message .= "An unverified enrollment is an inactive account.";
			$message .= "Please take note that the verification link is only valid 30 minutes after the receipt of it.\n\n";
			$message .= "<br /><br />";
			$message .= "To verify your enrollment, kindly click on the link below:\n\n";
			$message .= "<br /><br />";
			$message .= "<a href='{$link}' target='_blank' >{$link} </a> \n";
			$message .= "<br />";
			//$message .= "\n\n";
			//$message .= "Thank you so much and God Speed!.";
			$message .= "\n\n\n\n\n\n";
			$message .= "<br /><br /><br /><br /><br /><br />";
			//$message .= "The Management\n\n";
			$message .= "{$school_name}\n\n";
			$message .= "<br /><br />";
			$message .= "<span style='font-size:10px;'>This email and any files transmitted with it are confidential and intended solely for the use of ";
			$message .= "the individual or entity to whom they are addressed. If you have received this email in error ";
			$message .= "please notify the system manager. This message contains confidential information and is ";
			$message .= "intended only for the individual named. If you are not the named addressee you should not ";
			$message .= "disseminate, distribute or copy this e-mail. Please notify the sender immediately by e-mail if ";
			$message .= "you have received this e-mail by mistake and delete this e-mail from your system. If you are not  ";
			$message .= "the intended recipient you are notified that disclosing, copying, distributing or taking any action ";
			$message .= "in reliance on the contents of this information is strictly prohibited.</span>";
		
		$this->load->library('email');
		
		/*** config email **/
		$this->email->initialize(array(
			'mailtype' => 'html',
			'crlf' => "\r\n",
			'newline' => "\n"
		));
		/*** end config email **/
		
		$this->email->from($school_name_title,'Online Enrollment');
		$this->email->to($email_add);
		$this->email->subject('Please Verify Your Enrollment!');
		$this->email->message($message);
		$this->email->send();
	}
	
	private function _accronymizer($string = FALSE)
	{
		if($string !== FALSE)
		{
			$clean_string = htmlspecialchars(strip_tags($string));
			$number_of_words = str_word_count($clean_string,1);
			function acc($x)
			{
				if(strlen($x) > 1)
				{
					return $x[0];
				}
			}
			$accronym = array_map("acc",$number_of_words);
			return strtoupper(implode('',$accronym));
		}else{
			return NULL;
		}
	}
	
	private function _check_transaction()
	{
		if($this->session->userdata('enrollmenttransaction') == $this->_generate_transaction())
		{
		
		}else{
			$this->session->sess_destroy();
			redirect();
		}
	}
	
	private function _generate_token()
	{
		$key = "aIradhznlpsVeRae7qztven9lBNwUphE";
		$salt = sha1(date('d-d-d-d-d_d_d_d_d-d-d-d',time()).$key);
		$hash = str_pad($salt,5,'-');
		return $hash;
	}
	
	private function _generate_transaction()
	{
		if($this->session->userdata('enrollmenttransaction') == FALSE)
		{
			$this->session->userdata('enrollmenttransaction',$this->_generate_token());
		}
	}
	
	public function quitenrollment()
	{
		$this->session->sess_destroy();
		redirect('enrollment');
	}
	
	public function test_email()
	{
	
		$prof_child_lname = 'C';
		$prof_child_fname = 'A';
		$prof_child_mname = 'B';
		$link = 'http://google.com/';
		$prof_emailaddress = 'hay.an2ny@gmail.com';
		
		$this->_email_student_confirmation_link(
			$prof_child_lname,
			$prof_child_fname,
			$prof_child_mname,
			$link,
			$prof_emailaddress
		);
	}
}